﻿using FineUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.BranchCenter.BLL;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Center;
using ZHDJ.Data.Models.MassLine;
using ZHDJ.WebPage;

namespace ZHDJ.BranchCenter.Module.MassLine
{
    public partial class StudyActivityEdit : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        public string category
        {
            get
            {
                return this.Request.QueryString["category"] ?? "MassLineStudyActivity";
            }
        }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        private void BindData()
        {
        }

        private void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                PartyBranchStudyActivitie study = DB.PartyBranchStudyActivities.Find(id);
                if (study == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                this.txtTitle.Text = study.Title;
                this.ddlStudyType.SelectedValue = study.StudyType;

                StringBuilder sbParticipantLoginID = new StringBuilder();
                StringBuilder sbParticipantName = new StringBuilder();

                for (int i = 0; i < study.Record.Split(',').Length; i++)
                {
                    sbParticipantLoginID.Append(study.Record.Split(',')[i] + ",");
                    sbParticipantName.Append(ControlBusiness.GetMembersPickerText(study.Record.Split(',')[i]) + ",");
                }

                ppJoinMember.Value = sbParticipantLoginID.ToString().TrimEnd(',');
                ppJoinMember.Text = sbParticipantName.ToString().TrimEnd(',');

                StringBuilder sbSpeakLoginID = new StringBuilder();
                StringBuilder sbSpeakName = new StringBuilder();
                for (int i = 0; i < study.Participant.Split(',').Length; i++)
                {
                    sbSpeakLoginID.Append(study.Participant.Split(',')[i] + ",");
                    sbSpeakName.Append(ControlBusiness.GetMembersPickerText(study.Participant.Split(',')[i]) + ",");
                }
                ppSpeakMember.Value = sbSpeakLoginID.ToString().TrimEnd(',');
                ppSpeakMember.Text = sbSpeakName.ToString().TrimEnd(',');
                if (study.Status == 1)
                {
                    btnSaveClose.Visible = btnPublish.Visible = false;
                    btnUndo.Hidden = false;
                }
            }
            else
            {
                hdPhotoWallID.Text = StringHelper.NewID;
            }

            Grid1.DataSource = PartyPhotoWallImage.GetFileData(id);
            Grid1.DataBind();

        }
        #endregion

        #region Events

        private void SaveData(bool isPublish)
        {
            string id = GetQueryIntValue("id");
            string imageUrl = string.Empty;

            if (id != "")
            {
                //更新
                PartyBranchStudyActivitie study = DB.PartyBranchStudyActivities.Find(id);
                if (study == null)
                {
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }

                study.Title = txtTitle.Text.Trim();
                study.BranchID = this.BranchID;
                study.Status = isPublish ? 1 : 0;
                study.ModifyTime = DateTime.Now;
                study.ModifyBy = CurrentUser.LoginID;
                study.Participant = ppSpeakMember.Value;
                study.Record = ppJoinMember.Value;
                study.StudyType = ddlStudyType.SelectedValue;

                DB.SaveChanges();
            }
            else
            {
                PartyBranchStudyActivitie study = new PartyBranchStudyActivitie();
                study.ID = hdPhotoWallID.Text;
                study.Title = txtTitle.Text.Trim();
                study.Category = category;
                study.StudyType = ddlStudyType.SelectedValue;
                study.BranchID = this.BranchID;
                study.Status = isPublish ? 1 : 0;
                study.CreateTime = DateTime.Now;
                study.ModifyTime = DateTime.Now;
                study.CreateBy = CurrentUser.LoginID;
                study.ModifyBy = CurrentUser.LoginID;
                study.Participant = ppSpeakMember.Value;
                study.Record = ppJoinMember.Value;
                DB.PartyBranchStudyActivities.Add(study);

                DB.SaveChanges();
            }
        }

        private void SaveImageData()
        {
            if (Grid1.Rows.Count > 0)
            {
                foreach (GridRow row in Grid1.Rows)
                {
                    int rowIndex = row.RowIndex;
                    System.Web.UI.WebControls.TextBox txtDesc = (System.Web.UI.WebControls.TextBox)Grid1.Rows[rowIndex].FindControl("txtDesc");

                    string rowDataId = Convert.ToString(Grid1.DataKeys[rowIndex][0]);

                    if (txtDesc != null)
                    {
                        PartyPhotoWallImage image = DB.PartyPhotoWallImages.Find(rowDataId);
                        image.Describe = txtDesc.Text.Trim();

                        DB.SaveChanges();
                    }
                }
            }
        }

        /// <summary>
        /// 保存并关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData(false);
            SaveImageData();

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string wordId = GetSelectedDataKeyID(Grid1);

            if (e.CommandName == "Delete")
            {
                var del = DB.PartyPhotoWallImages.FirstOrDefault(t => t.ID == wordId);
                DB.PartyPhotoWallImages.Remove(del);
                DB.SaveChanges();

                Grid1.DataSource = PartyPhotoWallImage.GetFileData(hdPhotoWallID.Text);
                Grid1.DataBind();
            }
        }

        protected void fileImage_FileSelected(object sender, EventArgs e)
        {
            fileImage.Reset();
            UpFileResult upfileResult = UpFileBusiness.Upload(fileImage, CurrentUser.LoginID);

            PartyPhotoWallImage photo = new PartyPhotoWallImage();
            photo.ID = StringHelper.NewID;
            photo.PhotoWallID = hdPhotoWallID.Text;
            photo.FileID = upfileResult.FileID;
            photo.Describe = "";
            photo.CreateTime = DateTime.Now;
            photo.ModifyTime = DateTime.Now;
            photo.CreateBy = CurrentUser.LoginID;
            photo.ModifyBy = CurrentUser.LoginID;

            DB.PartyPhotoWallImages.Add(photo);

            DB.SaveChanges();

            Grid1.DataSource = PartyPhotoWallImage.GetFileData(hdPhotoWallID.Text);
            Grid1.DataBind();
        }
        #endregion

        protected void btnUndo_Click(object sender, EventArgs e)
        {
            SaveData(false);

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void btnPublish_Click(object sender, EventArgs e)
        {
            SaveData(true);

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
    }
}